package com.example;

/**
 * @Author loubobooo
 * @Description #50Pow(x, n)
 * @Date 2019/11/19
 */
public class PowxN {

    /**
     * @return
     * @Author loubobooo
     * @Description 实现 pow(x, n) ，即计算 x 的 n 次幂函数。
     * @Date 2019/11/19 10:26
     * @Param
     **/
    public double myPow(double x, int n) {
        if (x == 1 || x == 0) {
            return x;
        }
        if (n < 0) {
            n = -n;
            double v = recursivePow(x, n);
            return 1 / v;
        }
        return recursivePow(x, n);
    }

    private double recursivePow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        // 区分奇数和偶数
        if ((n & 1) == 0) {
            double temp = recursivePow(x, n / 2);
            return temp * temp;
        } else {
            // 奇数的情况
            double temp = recursivePow(x, n / 2);
            return temp * temp * x;
        }
    }


    public static void main(String[] args) {
        PowxN powxN = new PowxN();
        double v = powxN.recursivePow(10, 3);
        System.out.println(v);
    }
}
